#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

using namespace log_ns;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage " << argv[0] << " Server-ip Server-port" << std::endl;
        exit(0);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "socket error\n");
        exit(1);
    }
    LOG(DEBUG, "socket create success, sockfd:%d\n", sockfd);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr.s_addr);

    int n = ::connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect socket failed\n"
                  << std::endl;
        exit(2);
    }

    while (true)
    {
        std::cout << "Enter# ";
        std::string msg;
        std::getline(std::cin, msg);

        write(sockfd, msg.c_str(), msg.size());

        char echo_buffer[1024];
        int n = read(sockfd, echo_buffer, sizeof(echo_buffer) - 1);
        if (n > 0)
        {
            echo_buffer[n] = 0;
            std::cout << echo_buffer << std::endl;
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);
    return 0;
}